﻿using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Dapper.DBContext;
using Guoc.BigMall.Application.DTO;
using Guoc.BigMall.Application.Search;
using Guoc.BigMall.Application.ViewObject;
using Guoc.BigMall.Domain.Entity;
using Guoc.BigMall.Infrastructure;
using Guoc.BigMall.Infrastructure.Extension;

namespace Guoc.BigMall.Application.Facade
{
    public class MemberFacade : IMemberFacade
    {
        IDBContext _db;
        public MemberFacade(IDBContext dbContext)
        {
            this._db = dbContext;

        }        

        public IEnumerable<MemberListVo> GetList(Pager page, SearchMember search)
        {
            IEnumerable<MemberListVo> rows;
            dynamic param = new ExpandoObject();
            string where = "";
            if (search.RealName.NotNullOrEmpty())
            {
                where += " and  RealName like @RealName";
                param.RealName = string.Format("%{0}%", search.RealName);
            }

            if (search.Phone.NotNullOrEmpty())
            {
                where += " and Phone = @Phone";
                param.Phone =  search.Phone;
            }            

            string sql = @"Select * from Member where 1=1 {0} Order By  Id desc LIMIT {1},{2}";
            sql = string.Format(sql, where, (page.PageIndex - 1) * page.PageSize, page.PageSize);
            rows = _db.DataBase.Query<MemberListVo>(sql, param);
            var sqlcount = string.Format(" SELECT count(1) FROM Member WHERE 1=1 {0} ", where);
            page.Total = this._db.DataBase.ExecuteScalar<int>(sqlcount, param);

            return rows;
        }

        public int Create(MemberModel model)
        {
            if (_db.Table<Member>().Exists(n => n.Phone == model.Phone))
            {
                throw new Exception("电话已经注册!");
            }
            var entity = model.MapTo<Member>();
            entity.NickName = entity.RealName;
            // 添加 memberpass
            MemberPass pass = new MemberPass()
            {
                PassType = MemberPassType.phone.ToString(),
                PassId = entity.Phone
            };
            entity.PassList.Add(pass);

            _db.Insert(entity);
            _db.SaveChange();
            return entity.Id;
        }

        public void Update(MemberModel model)
        {
            if (_db.Table<Member>().Exists(n => n.Phone == model.Phone && n.Id != model.Id))
            {
                throw new Exception("电话重复!");
            }
            var entity = _db.Table<Member>().FirstOrDefault(n => n.Id == model.Id);
            var oldPhone = entity.Phone;
            model.MapTo(entity);
            entity.NickName = entity.RealName;
            // 如果修改了手机号，同步更改登录手机passid
            if (oldPhone != model.Phone) {
                var pass = _db.Table<MemberPass>().FirstOrDefault(n => n.PassId == oldPhone && n.MemberId == entity.Id&&n.PassType == MemberPassType.phone.ToString());
                if (pass != null) {
                    pass.PassId = model.Phone;
                    _db.Update(pass);
                }
            }
            _db.Update(entity);
            _db.SaveChange();
        }

        
    }
}
